<template>
    <div class="flex relative w-full overflow-hidden">
        <template v-if="errorsInfo">
            <div class="flex flex-col justify-center items-center bg-body w-full h-full rounded-xl">
                <el-result
                    icon="error"
                    title="文档加载失败"
                    :sub-title="errorsInfo"
                >
                    <template #extra>
                        <el-button
                            type="primary"
                            @click="jumpToHome"
                        >回到主页</el-button>
                    </template>
                </el-result>
            </div>
        </template>

        <template v-else>
            <div class="pdf-rendering">
                <div class="pdf-header">
                    <h2 class="font-semibold truncate mr-4">{{ detailData?.name }}</h2>
                    <pdf-controls
                        v-model:currentPage="statePdf.currentPage"
                        v-model:currentScale="statePdf.pdfScale"
                        :totalPages="statePdf.totalPages"
                        @switch-scale="pageScaleUpdate"
                        @switch-pager="pageJumpNumber"
                    />
                </div>
                <pdf-preview
                    ref="pdfPreviewRef"
                    :isErrors="statePdf.isError"
                    :isLoading="statePdf.isLoading"
                    :totalPages="statePdf.totalPages"
                    :pageHeight="statePdf.pageHeight"
                    :totalHeight="statePdf.totalHeight"
                    :visiblePages="statePdf.visiblePages"
                    :listenScroll="listenScroll"
                    :pageStyleObj="pageStylesObj"
                />
            </div>

            <doc-window
                :file-code="fileCode"
                :file-status="detailData.status"
                :file-error="detailData.error"
                :chat-avatar="detailData.chat_avatar"
                :auto-abstract="detailData.auto_abstract"
                :abstract="detailData.abstract"
                :translate="detailData.translate"
                :prompt-icon="detailData.prompt_icon"
                :prompt-name="detailData.prompt_name"
                :prompt-intro="detailData.prompt_intro"
            />
        </template>
    </div>
</template>

<script setup lang="ts">
import { watchDebounced } from '@vueuse/core'
import { usePdfRenderer } from '../hooks/usePdfRenderer'
import docsFilesApi from '~/api/apply/docs/files'
import docWindow from '../_components/doc-window.vue'
import pdfPreview from '../_components/_pdf/pdf-preview.vue'
import pdfControls from '../_components/_pdf/pdf-controls.vue'

// 路由对象
const route = useRoute()
const router = useRouter()

// 文件编号
const fileCode = ref<string>(String(route.query.code))

// 错误信息
const errorsInfo = ref<string>('')

// 详情数据
const detailData = ref({} as DocFilesDetailResponse)

// PDF引用
const pdfPreviewRef = ref<InstanceType<typeof pdfPreview>>()

// PDF实例
const {
    statePdf,
    listenScroll,
    pageStylesObj,
    initializePdf,
    pageJumpNumber,
    pageScaleUpdate,
    // pageTextSearch
} = usePdfRenderer()

/**
 * 查询数据
 */
const queryDetail = async () => {
    try {
        const code = String(route.query.code)
        detailData.value = await docsFilesApi.detail({ code })
    } catch (e: any) {
        errorsInfo.value = e.msg
    }
}

/**
 * 轮询机制
 */
const { start: startPolling, end: stopPolling } = usePolling(queryDetail, {
    key: 'docs',
    totalTime: 1000 * 60 * 10, // 最大轮询时间 10 分钟
    time: 1000 * 10,           // 每次轮询间隔 10 秒
    callback: () => {}         // 轮询结束回调
})

/**
 * 跳转主页
 */
const jumpToHome = () => {
    router.push({
        path: '/apply/docs/uploader'
    })
}

/**
 * 监听切换文件
 */
watchDebounced(
    () => route.query.code,
    async (val) => {
        await queryDetail()
        await initializePdf(detailData.value.path)
        fileCode.value = String(val)
        pdfPreviewRef.value!.setScrollTop(0)
        if ([0, 1].includes(detailData.value?.status)) {
            startPolling()
        } else {
            stopPolling()
        }
    },
    {
        debounce: 500,
        immediate: true
    }
)
</script>

<style scoped lang="scss">
.pdf-rendering {
    display: flex;
    flex-direction: column;
    width: 50%;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
    .pdf-header {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 52px;
        padding: 8px 16px;
        background-color: var(--el-bg-color);
        border-bottom: 1px solid var(--el-border-color-lighter);
        border-top-left-radius: 8px;
    }
}
</style>
